package com.isc.tcpCommunication02;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 1.编写一个服务器端和客户端
 * 2.服务器端在9999端口监听
 * 3.客户端连接到服务器端，发送"hello,server",并接收服务器端回发的"hello,client",再退出
 * 4.服务器端接收到客户端发送的信息，输出，并发送"hello,client",再退出
 */
public class Client {
    public static void main(String[] args) throws IOException {
        //客户端发送请求给服务器端
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("发送连接请求...");

        //发送数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,server".getBytes());
        socket.shutdownOutput();
        System.out.println("发送信息成功...");

        //接收服务器端回发的数据
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readlength = 0;
        while ((readlength = inputStream.read(buf)) != -1) {
            System.out.println("服务器发送的消息是:" + new String(buf, 0, readlength));
        }
        System.out.println("接收成功~");

        //关闭资源
        outputStream.close();
        inputStream.close();
        socket.close();
        System.out.println("客户端断开连接...");
    }
}
